from flask import current_app
from flask import g
from flask import request, jsonify

from app.api.house import house_blue
from app.models import House
from app.utils import constants
from app.utils.commons import user_login_data
from app.utils.image_storage import image_storage
from app.utils.response_code import RET


def demo():
    """
    3.4 上传房源图片
    作者：王丰
    :return:
    """

@house_blue.route('/<int:house_id>/image', methods=['POST'])
@user_login_data
def house_image(house_id):
    """

    3.4 上传房源图片

    :return:
    """
    if not g.user:
        return jsonify(errno=RET.NODATA,errmsg="用户未登录")

    house_image = request.files.get("house_image")

    if not house_image:
        return jsonify(errno=RET.NODATA,errmsg="图片不存在")

    image_name = image_storage(house_image.read())

    # 房子的图片地址添加到数据库
    try:
        house = House.query.get(house_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="取出房屋信息失败")

    if not house:
        return jsonify(errno=RET.NODATA,errmsg="房屋不存在")


    house.index_image_url = constants.QINIU_DOMIN_PREFIX + image_name


    data = {
        "url":constants.QINIU_DOMIN_PREFIX + image_name
    }

    return jsonify(errno="0",errmsg="OK",data=data)



@house_blue.route('/<int:house_id>')
@user_login_data
def house_index(house_id):

    if not house_id:
        return jsonify(errno=RET.OK,errmsg="参数不全")

    house = House.query.get(house_id)

    data = {
        "house":house.to_full_dict(),
        "user_id":g.user.id if g.user else 1
    }

    return jsonify(errno=RET.OK,errmsg="OK",data=data)





